<template>
  <tm-app ref="app">
    <tm-navbar title="编辑文件信息"></tm-navbar>
    <tm-sheet :margin="[32, 32]" :padding="[0, 32]">
      <view class="mb-32 mx-32 round-3 overflow">
        <tm-text
          :font-size="36"
          _class="text-weight-b"
          label="基础信息"
        ></tm-text>
        <view>
          <tm-icon
            v-if="file.icon"
            :font-size="144"
            :name="parseAvatar(file.icon).thumbnail"
            class="icon-img"
          ></tm-icon>
          <loadFileIcon
            v-else
            :size="144"
            :icon-type="file.typeName || '其他'"
            class="icon-img"
          />
          <view
            v-if="!flagFile"
            style="text-align: center; color: #0052d9"
            @click="editFile('icon')"
          >编辑图标</view
          >
        </view>
        <tm-cell
          @click="editFile('name')"
          rightColor="black"
          :rightText="file ? file.name : '文件名称'"
          :margin="[0, 0]"
          :titleFontSize="30"
          title="名称"
        >
        </tm-cell>
        <tm-cell :margin="[0, 0]" :titleFontSize="30" title="归属">
          <template v-slot:right>
            <tm-text
              color="grey"
              :font-size="30"
              :label="file && file.belongId ? file.belongId : '归属'"
            ></tm-text>
          </template>
        </tm-cell>
        <tm-cell :margin="[0, 0]" :titleFontSize="30" title="群组账号">
          <template v-slot:right>
            <tm-text
              color="grey"
              :font-size="30"
              :label="file.belong.avatar ? file.belong.name : '群组账号'"
            ></tm-text>
          </template>
        </tm-cell>
        <tm-cell :margin="[0, 0]" :titleFontSize="30" title="当前数据核">
          <template v-slot:right>
            <tm-text
              color="grey"
              :font-size="30"
              :label="
                file.storeName ? file.storeName : '当前数据核'
              "
            ></tm-text>
          </template>
        </tm-cell>
        <tm-cell
          @click="previewQC"
          rightText="查看"
          :margin="[0, 0]"
          :titleFontSize="30"
          title="群二维码"
        >
        </tm-cell>
        <tm-cell
          @click="editFile('remark')"
          :rightText="file ? file.remark : '文件简介'"
          :margin="[0, 0]"
          :titleFontSize="30"
          title="简介"
        >
        </tm-cell>
      </view>
    </tm-sheet>
    <tm-drawer
      v-model:show="showWin"
      @ok="submit"
      @cancel="showWin = false"
      ref="calendarView"
      placement="bottom"
      okText="提交"
      :height="200"
    >
      <tm-input
        v-model="textName"
        :type="textType === 'name' ? 'text' : 'textarea'"
        :focus="focused"
        :adjustPosition="true"
        :margin="[32, 16]"
        :placeholder="textType === 'name' ? '请输入名称' : '请输入简介'"
        confirmType="done"
      ></tm-input>
    </tm-drawer>
    <tm-drawer
      v-model:show="showQc"
      @ok="showQc = false"
      @cancel="showQc = false"
      ref="calendarViewQc"
      placement="center"
    >
    </tm-drawer>
  </tm-app>
</template>
<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, onBeforeUnmount } from 'vue'
import tmDrawer from '@/tmui/components/tm-drawer/tm-drawer.vue'
import orgCtrl from '@/ts/controller'
import { parseAvatar } from '@/ts/base'
import loadFileIcon from '@/components/icon/loadFileIcon.vue'
import tmNotification from '@/tmui/components/tm-notification/tm-notification.vue'
onBeforeUnmount(() => {
  uni.setStorageSync('shouldCallMethod', true)
})
const showWin = ref(false)
const showQc = ref(false)
const focused = ref(false)
const textType = ref('name')
const params = ref()
const file = ref()
const fileInfo = ref()
const textName = ref('')
const qrCodeUrl = ref('') // 存储二维码的 Base64 数据
const msg = ref<InstanceType<typeof tmNotification> | null>(null)
const flagFile = ref(false)
// const uqrcodeRef = ref<InstanceType<typeof uqrcode> | null>(null)
onLoad(options => {
  if (!options) return
  if (!options.id) return
  if (options) {
    try {
      // 解码并解析参数
      const parsedData = options
      params.value = parsedData // 存储参数
      uni.showLoading({ title: '加载中...' })
      searchFile()
    } catch (error) {
      console.error('解析参数错误:', error)
    }
  }
})
const searchFile = async () => {
  if (!params.value) return
  const fileData = await orgCtrl.searchFile(
    params.value.targetId,
    params.value.belongId,
    params.value.id,
    params.value.applicationId,
    params.value.isVirtual ?? false
  )
  if (fileData) {
    const store =
      'storeId' in fileData.metadata && fileData.metadata.storeId
        ? await orgCtrl.user.findEntityAsync(
            fileData.metadata.storeId as string
        )
        : undefined
    Object.assign(fileData.metadata, { storeName: store?.name })
    if(fileData.belong){
      Object.assign(fileData.metadata, { belong: fileData.belong })
    }
    file.value = fileData.metadata
    fileInfo.value = fileData
    if('accepts' in fileData && (fileData.accepts as string[]).length===1 && (fileData.accepts as string[])[0]==='文件'){
      flagFile.value = true
    }
    if('filedata'in fileData){
      flagFile.value = true
    }
  }
  uni.hideLoading()
}
const editFile = (type: string) => {
  if(type === 'remark'&&flagFile.value)return false
  if(type === 'name'&&flagFile.value&&file.value.name==='文件夹')return false
  if(type === 'icon') {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0]
        if(!tempFilePath)return false
        // 获取文件扩展名
        const extension = tempFilePath.split('.').pop()!.toLowerCase()
        // 根据扩展名确定MIME类型
        const mimeType = {
          'jpg': 'image/jpeg',
          'jpeg': 'image/jpeg',
          'png': 'image/png',
          'gif': 'image/gif',
          'webp': 'image/webp'
        }[extension] || 'image/jpeg'  // 默认使用 jpeg
        try {
          const fs = uni.getFileSystemManager();
          const fileData = fs.statSync(tempFilePath) as UniApp.Stats;
          const fileName = tempFilePath.split('/').pop() || 'image.jpg';
          const uploadResult = await fileInfo.value.directory.createFile(
            fileName,
            {
              size: fileData.size, // 实际大小会在 fileUpdate 中获取
              type: mimeType,
              path: tempFilePath // 添加路径属性
            }
          )
          if (uploadResult) {
            //解析头像
            const result = JSON.stringify(uploadResult.shareInfo())

            const success = await fileInfo.value.coll.replace({
              ...fileInfo.value.metadata,
              icon: result,
              directoryId: file.value.directoryId,
              typeName: file.value.typeName
            })
            if (success) {
              file.value.icon = result
              msg.value?.show({ label: '修改成功' })
            }
          }
        } catch (error) {
          console.error('上传失败:', error)
          msg.value?.show({ label: '上传失败' })
        }
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        msg.value?.show({ label: '选择图片失败' })
      }
    })
  } else {
    showWin.value = true
    focused.value = true
    if (type === 'name') {
      textType.value = 'name'
      textName.value = file.value?.name
    } else if (type === 'remark') {
      textType.value = 'remark'
      textName.value = file.value?.remark
    }
  }
}
const submit = async () => {
  //提交
  const data = {}
  if (textType.value === 'name') {
    (data as { name?: string }).name = textName.value
  } else if (textType.value === 'remark') {
    (data as { remark?: string }).remark = textName.value
  }
  const success = await fileInfo.value.coll.replace({
    ...fileInfo.value.metadata,
    ...data,
    directoryId: file.value.directoryId,
    typeName: file.value.typeName
  })
  if (success) {
    file.value.name = success.name
    file.value.remark = success.remark
    msg.value?.show({ label: '修改成功' })
  }
}
const previewQC = () => {
  if (file.value?.id) {
    qrCodeUrl.value = `https://assetcloud.zj.gov.cn/${file.value.id}`
    showQc.value = true
  } else {
    msg.value?.show({ label: '无效的ID' })
  }
}
</script>
<style lang="scss">
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .qrcode-wrapper {
    width: 400rpx;
    height: 400rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
  }
}
</style>
